const express = require('express');
const router = express.Router();
const db = require('../config/db')

let jwt = require('jsonwebtoken')
function token(obj){
    const username = obj.username;
    //token私钥
    const PRIVATE_KEY = 'tokenKey'
    //token时效
    const JWT_EXPIRED = 60 * 60;
    const Token = jwt.sign({ username },PRIVATE_KEY,{expiresIn:JWT_EXPIRED})
    return Token
}

/* GET users listing. */
router.post('/login', function (req, res, next) {
    let data = {
        phoneNum: req.body.phoneNum,
        password: req.body.password
    }
    db.findOne('test2',data,(err,result)=> {
        if(result.length === 0) {
            res.status(200).send({text:'账号不存在或密码错误'})
        }else {
            console.log(result)
            const Token = token(data);
            res.status(200).send({text: '登录成功',token: Token, username:result[0].username})
        }
    });
});


router.post('/register', function (req, res, next) {
    let data = {
        username: req.body.username,
        phoneNum: req.body.phoneNum,
        password: req.body.password,
    }
    db.findOne('test2',{phoneNum: data.phoneNum},(err,result)=> {
        if(result.length === 0) {
            db.insertOne('test2',data).then(()=> {
                res.status(200).send({text: '注册成功'})
            })
        }else {
            res.status(200).send({text: '账号已经存在'})
        }
    });
});

module.exports = router;
